import { reactive } from 'vue'
import type { QueryField, QueryState } from '../types'

export function useQueryForm(fields: QueryField[]) {
  // 表单状态
  const state = reactive<QueryState>({
    form: {},
    initialForm: {},
    loading: false,
  })

  // 初始化表单数据
  const initForm = () => {
    const form: Record<string, any> = {}
    const initialForm: Record<string, any> = {}

    fields.forEach((field) => {
      if (field.defaultValue !== undefined) {
        form[field.prop] = field.defaultValue
        initialForm[field.prop] = field.defaultValue
      }
    })

    state.form = form
    state.initialForm = initialForm
  }

  // 重置表单
  const resetForm = () => {
    state.form = { ...state.initialForm }
  }

  // 设置表单数据
  const setForm = (data: Record<string, any>) => {
    state.form = { ...state.form, ...data }
  }

  // 设置加载状态
  const setLoading = (loading: boolean) => {
    state.loading = loading
  }

  // 初始化
  initForm()

  return {
    state,
    resetForm,
    setForm,
    setLoading,
  }
}
